package com.lmuse.xmr.foodspotting.ui.recipe;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lmuse.xmr.foodspotting.R;
import com.lmuse.xmr.foodspotting.constants.Recipe;
import com.lmuse.xmr.foodspotting.db.CollectPresenterImpl;
import com.lmuse.xmr.foodspotting.db.Contract;
import com.lmuse.xmr.foodspotting.db.FollowPresenterImpl;
import com.lmuse.xmr.foodspotting.db.RecipePresenterImpl;
import com.lmuse.xmr.foodspotting.db.UserPresenterImpl;
import com.lmuse.xmr.foodspotting.model.User;
import com.lmuse.xmr.foodspotting.util.StringUtils;
import com.sendtion.xrichtext.RichTextView;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class RecipeActivity extends AppCompatActivity implements Contract.RecipeView, Contract.UserView,
        Contract.CollectView, Contract.FollowView{

    private TextView titleTv;
    private TextView authorTv;
    private TextView deleteTv;
    private ImageView coverImg;
    private Button attention; //关注
    private ImageButton collector;
    private RichTextView contentView;
    private ProgressDialog loadingDialog;
    private Subscription subsLoading;

    private Contract.RecipePresenter recipePresenter;
    private Contract.UserPresenter userPresenter;
    private Contract.CollectPresenter collectPresenter;
    private Contract.FollowPresenter followPresenter;

    private String objectId;
    private String content;
    private User user;
    private int isCollectExist; //"我"是否收藏了当前的菜谱
    private boolean isCollect = false; //"我"是否收藏了当前的菜谱
    private User author;
    private int isFollowingExist; //"我"是否关注了当前的作者
    private boolean isFollowing = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe);
        objectId = getIntent().getStringExtra(Recipe.ID);
        recipePresenter = new RecipePresenterImpl(this);
        userPresenter = new UserPresenterImpl(this);
        collectPresenter = new CollectPresenterImpl(this);
        followPresenter = new FollowPresenterImpl(this);
        initView();
        userPresenter.getUserInfoCache();
        recipePresenter.queryRecipe(Recipe.ID, objectId, 1);
        collectPresenter.queryCollecting();
    }

    void initView() {
        titleTv = (TextView) findViewById(R.id.tv_recipe_title);
        authorTv = (TextView) findViewById(R.id.tv_recipe_author);
        deleteTv = (TextView) findViewById(R.id.tv_delete);
        coverImg = (ImageView) findViewById(R.id.img_recipe_cover);
        contentView = (RichTextView) findViewById(R.id.et_display_content);
        attention = (Button) findViewById(R.id.btn_recipe_attention);
        collector = (ImageButton) findViewById(R.id.imgBtn_recipe_collector);

        deleteTv.setOnClickListener(new ButtonClickListener());
        attention.setOnClickListener(new ButtonClickListener());
        collector.setOnClickListener(new ButtonClickListener());

        loadingDialog = new ProgressDialog(this);
        loadingDialog.setMessage("数据加载中...");
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.show();
    }

    /**
     * 异步方式显示数据
     * @param html
     */
    private void showDataSync(final String html){

        subsLoading = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                showEditData(subscriber, html);
            }
        })
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())//生产事件在io
                .observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        if (loadingDialog != null){
                            loadingDialog.dismiss();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (loadingDialog != null){
                            loadingDialog.dismiss();
                        }
                        Toast.makeText(RecipeActivity.this, "解析错误：图片不存在或已损坏", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(String text) {
                        if (text.contains("<img") && text.contains("src=")) {
                            //imagePath可能是本地路径，也可能是网络地址
                            String imagePath = StringUtils.getImgSrc(text);
                            contentView.addImageViewAtIndex(contentView.getLastIndex(), imagePath);
                        } else {
                            contentView.addTextViewAtIndex(contentView.getLastIndex(), text);
                        }
                    }
                });

    }

    /**
     * 显示数据
     * @param html
     */
    private void showEditData(Subscriber<? super String> subscriber, String html) {
        try {
            List<String> textList = StringUtils.cutStringByImgTag(html);
            for (int i = 0; i < textList.size(); i++) {
                String text = textList.get(i);
                subscriber.onNext(text);
            }
            subscriber.onCompleted();
        } catch (Exception e){
            e.printStackTrace();
            subscriber.onError(e);
        }
    }

    class ButtonClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {

                case R.id.tv_delete:
                    recipePresenter.deleteRecipe(objectId);
                    break;
                case R.id.btn_recipe_attention:
                    if (isFollowing) {
                        followPresenter.unFollowing(author.getObjectId());
                    }else {
                        followPresenter.addFollowing(author.getObjectId());
                    }
                    break;
                case R.id.imgBtn_recipe_collector:
                    if (isCollect) {
                        collectPresenter.cancelCollectRecipe(objectId);
                    }else {
                        collectPresenter.collectRecipe(objectId);
                    }
                    break;
            }
        }
    }

    @Override
    public void onUploadingImg(Integer value) {

    }

    @Override
    public void onUploadingImg(int curIndex, int curPercent, int total, int totalPercent) {

    }

    @Override
    public void onUploadImgSuccess(BmobFile cover) {

    }

    @Override
    public void onUploadImgSuccess(List<String> urls) {

    }

    @Override
    public void onUploadImgFailed(String msg) {

    }

    @Override
    public void onAddRecipeSuccess() {

    }

    @Override
    public void onAddRecipeFailed(String msg) {

    }

    @Override
    public void onQueryRecipeSuccess(final com.lmuse.xmr.foodspotting.model.Recipe recipe) {
        titleTv.setText(recipe.getTitle());
        Glide.with(this).load(recipe.getCoverUrl()).into(coverImg);
        userPresenter.queryUserById(recipe.getAuthor().getObjectId());
        contentView.post(new Runnable() {
            @Override
            public void run() {
                contentView.clearAllLayout();
                showDataSync(recipe.getContent());
            }
        });
    }

    @Override
    public void onQueryRecipeSuccess(List<com.lmuse.xmr.foodspotting.model.Recipe> recipeList) {
        loadingDialog.dismiss();
    }

    @Override
    public void onQueryRecipeFailed(String msg) {
        loadingDialog.dismiss();
        Toast.makeText(this, "请求数据失败！(" + msg + ")", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCollectRecipeSuccess() {
        Toast.makeText(this, "收藏成功！", Toast.LENGTH_SHORT).show();
        isCollect = true;
        collector.setImageResource(R.drawable.like);
    }

    @Override
    public void onCollectRecipeFailed(String msg) {
        Toast.makeText(this, "收藏失败！(" + msg + ")", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCancelCollectSuccess() {
        Toast.makeText(this, "已取消收藏!", Toast.LENGTH_SHORT).show();
        isCollect = false;
        collector.setImageResource(R.drawable.unlike);
    }

    @Override
    public void onCancelCollectFailed(String msg) {
        Toast.makeText(this, "取消收藏失败！(" + msg + ")", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onQueryCollectingSuccess(List<com.lmuse.xmr.foodspotting.model.Recipe> recipeList) {
        List<String> recipeIdList = new ArrayList<>();
        for (com.lmuse.xmr.foodspotting.model.Recipe recipe : recipeList) {
            recipeIdList.add(recipe.getObjectId());
        }
        if (user != null) { //用户已登录情况下查询才是有效的
            isCollectExist = recipeIdList.indexOf(objectId); //当前菜谱是否在用户已收藏的列表中
            if (isCollectExist != -1) { //已收藏
                isCollect = true;
                collector.setImageResource(R.drawable.like);
            }else {//未收藏
                isCollect = false;
            }
        }
    }

    @Override
    public void onQueryCollectingFailed(String msg) {
        Toast.makeText(this, "请求收藏列表失败！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSignUpSuccess(User user) {

    }

    @Override
    public void onSignUpFailed(String msg) {

    }

    @Override
    public void onSignInSuccess(User user) {

    }

    @Override
    public void onSignInFailed(String msg) {

    }

    @Override
    public void onUserInfoCache(User user) {
        if (user != null) {
            this.user = user;
            if (user.getObjectId().equals("2qLBRRRz")) {
                deleteTv.setVisibility(View.VISIBLE);
                deleteTv.setClickable(true);
            }else {
                deleteTv.setVisibility(View.INVISIBLE);
                deleteTv.setClickable(false);
            }
        }
    }

    @Override
    public void onUpdateUserSuccess() {

    }

    @Override
    public void onUpdateUserFailed(String msg) {

    }

    @Override
    public void onRequestEmailVerifyResult(BmobException e) {

    }

    @Override
    public void onResetPasswordByEmailResult(BmobException e) {

    }

    @Override
    public void onQueryUserByIdSuccess(User user) {
        this.author = user;

        if (author.getNickname() != null) {
            authorTv.setText("作者：" + author.getNickname());
        }else {
            authorTv.setText("作者：" + author.getUsername());
        }

        if (author.getUsername().equals("admin")) {
            attention.setClickable(false);
            attention.setText("默认关注");
            attention.setBackgroundColor(getResources().getColor(R.color.colorLightGray));
        }

        followPresenter.queryFollowings(); //获取到作者之后再查询
    }

    @Override
    public void onQueryUserByIdFailed(String msg) {
        Toast.makeText(this, "获取作者信息失败！(" + msg + ")", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onAddFollowingSuccess() {
        Toast.makeText(this, "关注成功！", Toast.LENGTH_SHORT).show();
        attention.setBackgroundColor(getResources().getColor(R.color.colorLightGray));
        attention.setText("已关注");
        isFollowing = true;
    }

    @Override
    public void onAddFollowingFailed(String msg) {
        Toast.makeText(this, "关注失败！(" + msg + ")", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUnFollowingSuccess() {
        Toast.makeText(this, "取消关注成功！", Toast.LENGTH_SHORT).show();
        attention.setBackgroundResource(R.drawable.btn_style_green_turn_dark_circle);
        attention.setText("+关注");
        isFollowing = false;
    }

    @Override
    public void onUnFollowingFailed(String msg) {
        Toast.makeText(this, "取消关注失败！(" + msg + ")", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onQueryFollowingSuccess(List<User> userList) {
        List<String> userIdList = new ArrayList<>();
        for (User user : userList) {
            userIdList.add(user.getObjectId());
        }
        if (user != null) { //用户已登录情况下查询才是有效的
            isFollowingExist = userIdList.indexOf(author.getObjectId()); //当前作者是否在用户已关注的列表中
            if (isFollowingExist != -1) { //已关注
                isFollowing = true;
                if (!author.getUsername().equals("admin")) {
                    attention.setBackgroundColor(getResources().getColor(R.color.colorLightGray));
                    attention.setText("已关注");
                }
            }else {//未收藏
                isFollowing = false;
            }
        }
    }

    @Override
    public void onQueryFollowingFailed(String msg) {
        Toast.makeText(this, "获取我的关注失败！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onQueryFollowerSuccess(List<User> userList) {

    }

    @Override
    public void onQueryFollowerFailed(String msg) {

    }

    @Override
    public void onQueryFollowerAmountSuccess(Integer num) {

    }

    @Override
    public void onQueryFollowerAmountFailed(String msg) {

    }

    @Override
    public void onQueryUserAmountSuccess(int size) {

    }

    @Override
    public void onQueryUserAmountFailed(String msg) {

    }

    @Override
    public void onQueryByKeySuccess(List<User> userList) {

    }

    @Override
    public void onQueryByKeyFailed(String msg) {

    }

    @Override
    public void onQueryKeySuccess(List<com.lmuse.xmr.foodspotting.model.Recipe> recipeKeyList) {

    }

    @Override
    public void onQueryKeyFailed(String msg) {

    }

    @Override
    public void onDeleteRecipeSuccess() {
        Toast.makeText(this, "删除菜谱成功！", Toast.LENGTH_SHORT).show();
        this.finish();
    }

    @Override
    public void onDeleteRecipeFailed(String msg) {
        Toast.makeText(this, "删除菜谱失败！", Toast.LENGTH_SHORT).show();
    }
}
